import {Component, NgZone, ViewChild} from '@angular/core';
import {Content, Events, IonicPage, NavController, NavParams, Platform, ToastController} from 'ionic-angular';
import {SideMenuService} from "../../../services/common/side-menu.service";
import {TabsPage} from "../../tabs/tabs";
import * as moment from 'moment';
import {DateService} from '../../../services/common/date.service';

/**
 * Generated class for the PolicyFilterPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@IonicPage()
@Component({
  selector: 'page-policy-filter',
  templateUrl: 'policy-filter.html',
    providers: [SideMenuService,DateService]
})
export class PolicyFilterPage {

    //主险名称状态
    mainRiskExpand: boolean = true;

    //保单状态是否折叠
    policyStatusExpand: boolean = false;

    //主险名称状态
    cbfxRisk: boolean = false;
    cbakRisk: boolean = false;
    cbfxzxbRisk: boolean = false;
    cbakzxbRisk: boolean = false;
    otherRisk: boolean = false;

    //保单状态
    jfqnPolicy: boolean = false;
    hmbfPolicy: boolean = false;
    bfyjqPolicy: boolean = false;
    jejqPolicy: boolean = false;
    htqmPolicy: boolean = false;
    otherPolicy: boolean = false;

    //搜索条件 绑定
    effectiveStartTime = '';
    effectiveEndTime = '';
    paymentStartTime = '';
    paymentEndTime = '';
    annualPremiumStart = '';
    annualPremiumEnd = '';

    selfKeyword = '';

    //搜索条件
    queryRecord: any;

    //验证
    annualValidPremiumStatus: boolean = true;
    effectiveDateValidStatus: boolean = true;
    paymentDateValidStatus: boolean = true;

    //结果
    allValidResult: boolean = true;

    // 时间插件--年月日汉字填充
    private pickerOptions = {
        cssClass: 'filter-add-picker'
    };

    @ViewChild(Content) content: Content;
    openRoot = (name, index) => this.openTab(name, index);
    // 年度列表
    private yearList:any[]=[];

  constructor(public navCtrl: NavController,
              private sideMenuService: SideMenuService,
              public tabsPage: TabsPage,
              public platform: Platform,
              public zone: NgZone,
              public toastCtrl: ToastController,
              public navParams: NavParams,
              public dateService:DateService,
              public events: Events
              ) {
      this.queryRecord = this.navParams.get('record');
      this.yearList=this.dateService.getYearList(1900);
      // console.log(this.queryRecord);

      if (this.queryRecord) {
          this.cbfxRisk = this.queryRecord.cbfxRisk;
          this.cbakRisk = this.queryRecord.cbakRisk;
          this.cbfxzxbRisk = this.queryRecord.cbfxzxbRisk;
          this.cbakzxbRisk = this.queryRecord.cbakzxbRisk;
          this.otherRisk= this.queryRecord.otherRisk;
          this.jfqnPolicy = this.queryRecord.jfqnPolicy;
          this.hmbfPolicy = this.queryRecord.hmbfPolicy;
          this.bfyjqPolicy = this.queryRecord.bfyjqPolicy;
          this.jejqPolicy = this.queryRecord.jejqPolicy;
          this.htqmPolicy= this.queryRecord.htqmPolicy;
          this.otherPolicy = this.queryRecord.otherPolicy;
          this.effectiveStartTime= this.queryRecord.effectiveStartTime;
          this.effectiveEndTime = this.queryRecord.effectiveEndTime;
          this.paymentStartTime = this.queryRecord.paymentStartTime;
          this.paymentEndTime = this.queryRecord.paymentEndTime;
          this.annualPremiumStart = this.queryRecord.annualPremiumStart;
          this.annualPremiumEnd= this.queryRecord.annualPremiumEnd;
          this.selfKeyword = this.queryRecord.selfKeyword;

          this.policyStatusExpand = this.queryRecord.policyStatusExpand;
      }
  }

  ionViewDidLoad() {
      // if (this.platform.is('ios')) {
      //     let datetimes = document.querySelectorAll('ion-datetime');
      //     Array.prototype.forEach.call(datetimes, (el) => {
      //         el.addEventListener('click', () => {
      //             this.content.scrollTo(0, this.content.scrollTop + 1);
      //         });
      //     });
      // }

      if (this.platform.is('ios')) {
          // document.querySelector('body').addEventListener('touchend', function(e) {
          //     if(e.target.className != 'input') {
          //         document.querySelector('.input').blur();
          //     }
          // });
      }
  }

    ionViewWillLeave() {
        this.content.scrollToTop();
    }

    openMenu(myEvent) {
        this.sideMenuService.openSideMenu(myEvent)
    }

    openTab(name, index) {
        this.navCtrl.popToRoot()
        this.tabsPage.openPage({name: name, index: index});
    }

    //折叠主险名称
    expandMainRisk() {
      this.mainRiskExpand = !this.mainRiskExpand;
    }

    //折叠保单状态
    expandPolicyStatus() {
      this.policyStatusExpand = !this.policyStatusExpand;
    }

    changeStatus(name: string) {
      switch (name) {
          case 'cbfxRisk': this.cbfxRisk = !this.cbfxRisk;break;
          case 'cbakRisk': this.cbakRisk = !this.cbakRisk;break;
          case 'cbfxzxbRisk': this.cbfxzxbRisk = !this.cbfxzxbRisk;break;
          case 'cbakzxbRisk': this.cbakzxbRisk = !this.cbakzxbRisk;break;
          case 'otherRisk': this.otherRisk = !this.otherRisk;break;

          case 'jfqnPolicy': this.jfqnPolicy = !this.jfqnPolicy;break;
          case 'hmbfPolicy': this.hmbfPolicy = !this.hmbfPolicy;break;
          case 'bfyjqPolicy': this.bfyjqPolicy = !this.bfyjqPolicy;break;
          case 'jejqPolicy': this.jejqPolicy = !this.jejqPolicy;break;
          case 'htqmPolicy': this.htqmPolicy = !this.htqmPolicy;break;
          case 'otherPolicy': this.otherPolicy = !this.otherPolicy;break;
      }
    }

    //完成
    completeFilter() {
      let mainRiskArr = [], policyStatusArr=[];
      let mainRiskCondition = '', policyStatusCondition='';

      //主险名称
      if (this.cbfxRisk)
          mainRiskArr.push('CCC');
      if (this.cbakRisk)
          mainRiskArr.push('CDC');
      if (this.cbfxzxbRisk)
          mainRiskArr.push('CEC');
      if (this.cbakzxbRisk)
          mainRiskArr.push('CFC');
      if (this.otherRisk)
          mainRiskArr.push('#CCC,CDC,CEC,CFC');
      if (mainRiskArr.length > 0) {
          mainRiskCondition = mainRiskArr.join(',');
      }

      //保单状态
      if (this.jfqnPolicy)
          policyStatusArr.push('1');
      if (this.hmbfPolicy)
          policyStatusArr.push('2');
      if (this.bfyjqPolicy)
          policyStatusArr.push('3');
      if (this.jejqPolicy)
          policyStatusArr.push('5');
      if (this.htqmPolicy)
          policyStatusArr.push('F');
      if (this.otherPolicy)
          // policyStatusArr.push('#0,4,B,C,D,E,H,J,L,N,R,S,X');
          policyStatusArr.push('#1,2,3,5,F');
      if (policyStatusArr.length > 0) {
          policyStatusCondition = policyStatusArr.join(',');
      }

      let condition = {
          "productCode": mainRiskCondition ? mainRiskCondition : '',
          "effectiveStartTime": this.effectiveStartTime ? moment(new Date(this.validDateString(this.effectiveStartTime)+' 00:00:00')).unix() : '',
          "effectiveEndTime": this.effectiveEndTime ? moment(new Date(this.validDateString(this.effectiveEndTime)+' 00:00:00')).unix() : '',
          "paymentStartTime": this.paymentStartTime ? moment(new Date(this.validDateString(this.paymentStartTime)+' 00:00:00')).unix() : '',
          "paymentEndTime": this.paymentEndTime ? moment(new Date(this.validDateString(this.paymentEndTime)+' 00:00:00')).unix() : '',
          "annualPremiumStart": this.annualPremiumStart ? this.annualPremiumStart : '',
          "annualPremiumEnd": this.annualPremiumEnd ? this.annualPremiumEnd : '',
          "status": policyStatusCondition ? policyStatusCondition : '',
          "keyword": this.selfKeyword ? this.selfKeyword : ''
          // "not-loading": "0"
      };

      let record = {
          "cbfxRisk": this.cbfxRisk,
          "cbakRisk": this.cbakRisk,
          "cbfxzxbRisk": this.cbfxzxbRisk,
          "cbakzxbRisk": this.cbakzxbRisk,
          "otherRisk": this.otherRisk,
          "jfqnPolicy": this.jfqnPolicy,
          "hmbfPolicy": this.hmbfPolicy,
          "bfyjqPolicy": this.bfyjqPolicy,
          "jejqPolicy": this.jejqPolicy,
          "htqmPolicy": this.htqmPolicy,
          "otherPolicy": this.otherPolicy,
          "effectiveStartTime": this.effectiveStartTime,
          "effectiveEndTime": this.effectiveEndTime,
          "paymentStartTime": this.paymentStartTime,
          "paymentEndTime": this.paymentEndTime,
          "annualPremiumStart": this.annualPremiumStart,
          "annualPremiumEnd": this.annualPremiumEnd,
          "selfKeyword": this.selfKeyword,
          "policyStatusExpand": this.policyStatusExpand
      };

      // console.log('condition--------------');
      // console.log(condition);

      //   let index = this.navCtrl.last().index;
      //   console.log('index', index);
      //   let count = 0;
      //
      // this.navCtrl.push('PolicyListPage', {'condition':condition, 'record': record}).then(() => {
      //     this.navCtrl.remove(index-1,index);
      // });
      //   let flag= true;
      //   this.events.publish('policy:filter',condition,record,flag);
      //   console.log('publish');
        let flag= true;
        this.navCtrl.pop().then(() => {
            this.events.publish('policy:filter',condition,record,flag);
        });
    }


    //重置
    resetFilter() {
        this.cbfxRisk = false;
        this.cbakRisk = false;
        this.cbfxzxbRisk = false;
        this.cbakzxbRisk = false;
        this.otherRisk = false;

        this.jfqnPolicy = false;
        this.hmbfPolicy = false;
        this.bfyjqPolicy = false;
        this.jejqPolicy = false;
        this.htqmPolicy = false;
        this.otherPolicy = false;

        this.effectiveStartTime = '';
        this.effectiveEndTime = '';
        this.paymentStartTime = '';
        this.paymentEndTime = '';
        this.annualPremiumStart = '';
        this.annualPremiumEnd = '';

        this.selfKeyword = '';

        this.annualValidPremiumStatus = true;
        this.effectiveDateValidStatus = true;
        this.paymentDateValidStatus = true;

        this.allValidResult = true;
    }

    clearEffectiveDate() {
        this.effectiveStartTime = '';
        this.effectiveEndTime = '';
        this.effectiveDateValidStatus = true;
        this.validAllStatus();
    }

    clearPaymentDate() {
        this.paymentStartTime = '';
        this.paymentEndTime = '';
        this.paymentDateValidStatus = true;
        this.validAllStatus();
    }

    goBack() {
        this.navCtrl.pop().then(() => {
            this.events.publish('policy:filter','','',false);
        });
        // this.navCtrl.push('PolicyListPage');
        // this.navCtrl.popToRoot();
    }

    showToast(msg: string) {
      this.toastCtrl.create({
          message: msg,
          position: 'middle',
          duration: 1200
      }).present();
    }

    scrollTo($event) {

        const top = $event.target.offsetParent.offsetTop;
        // if (this.platform.is('ios')) {
        //     this.zone.run(() => {
        //         this.content.scrollTo(0, top);
        //     });
        //     // this.focusStatus = true;
        // } else {
        //     setTimeout(() => {
        //         this.content.scrollTo(0, top);
        //     }, 500);
        // }

        setTimeout(() => {
            this.content.scrollTo(0, top);
        }, 500);
    }

    scrollTo2($event) {
        const top = $event.target.offsetParent.offsetParent.offsetTop;

        // if (this.platform.is('ios')) {
        //     this.zone.run(() => {
        //         this.content.scrollTo(0, top);
        //     });
        //     // this.focusStatus = true;
        // } else {
        //
        // }
        setTimeout(() => {
            this.content.scrollTo(0, top);
        }, 500);
    }

    checkInteger($event) {
        console.log($event);
        let val = $event.value.replace(/[^0-9]/ig, '');
        if ($event.value.length > 1) {
            val = val.replace(/^[0]+/, '');
        }
        $event.value = val;
    }

    validEffectiveDate() {

        if (this.effectiveStartTime && this.effectiveEndTime) {
            if (new Date(this.effectiveStartTime) > new Date(this.effectiveEndTime)) {
                this.effectiveDateValidStatus = false;
                this.showToast('保单生效日范围输入有误');
            } else {
                this.effectiveDateValidStatus = true;
            }
        } else if (!this.effectiveStartTime && !this.effectiveEndTime) {
            this.effectiveDateValidStatus = true;
        } else {
            // this.effectiveDateValidStatus = false;
            // this.showToast('请选择完整的保单生效日范围或不填！');
            this.effectiveDateValidStatus = true;
        }

        this.validAllStatus();
    }

    validPaymentDate() {
        if (this.paymentStartTime && this.paymentEndTime) {
            if (new Date(this.paymentStartTime) > new Date(this.paymentEndTime)) {
                this.paymentDateValidStatus = false;
                this.showToast('下期应缴保费日范围输入有误');
            } else {
                this.paymentDateValidStatus = true;
            }
        } else if (!this.paymentStartTime && !this.paymentEndTime){
            this.paymentDateValidStatus = true;
        } else {
            // this.paymentDateValidStatus = false;
            // this.showToast('请选择下期应缴保费日范围或不填！');
            this.paymentDateValidStatus = true;
        }

        this.validAllStatus();
    }

    validAnnualPremium($event) {

      if (this.annualPremiumStart && this.annualPremiumEnd) {
          if (Number(this.annualPremiumStart) > Number(this.annualPremiumEnd)){
              this.annualValidPremiumStatus = false;
              this.showToast('年缴保费范围输入有误');
          } else {
              this.annualValidPremiumStatus = true;
          }
      } else if (!this.annualPremiumStart && !this.annualPremiumEnd) {
          this.annualValidPremiumStatus = true;
      } else {
          // this.annualValidPremiumStatus = false;
          // this.showToast('请输入完整年缴保费范围或不填！');
          this.annualValidPremiumStatus = true;
      }

      this.validAllStatus();
    }

    validAllStatus() {
      if (this.effectiveDateValidStatus && this.paymentDateValidStatus && this.annualValidPremiumStatus) {
          this.allValidResult = true;
      } else {
          this.allValidResult = false;
      }

      console.log(this.allValidResult);

    }

    validDateString(dateStr: string) {
      return dateStr.replace('-','/')
          .replace('-','/');
    }

    makeBlur($event) {
      if (this.platform.is('ios')) {

          if($event.target.className != 'text-input text-input-ios') {
              let elements = document.querySelectorAll('.text-input');
              console.log(elements);
              Object.keys(elements).map((key) => {
                  elements[key].blur();
              });
          }
      }
    }

}
